package com.socio.behaviors;

import java.util.Arrays;
import java.util.List;

import javax.jdo.PersistenceManager;

import com.google.appengine.api.datastore.Key;
import com.socio.model.Day;
import com.socio.utils.FieldAccessor;
import com.socio.utils.FieldAccessor.FieldAccessorField;

/**
 *
 * @author potlow
 */
public class DayKeyBehavior extends DayBehavior {

	/**
	 * Makes sure search filter is valid type
	 * 
	 * @param value filter value
	 * @return value of correct type
	 */
	private Key checkFilter(Object value) {
		Key key;
        if (value instanceof Key) {
            key = (Key) value;
        } else {
            throw new IllegalArgumentException("Search value must be a Key");
        }
        
        return key;
	}
	
    @Override
    public List<Object> read(Object filter, List<FieldAccessorField> touchFields) {
    	PersistenceManager pm = pmf.getPersistenceManager();
    	
    	Key key = checkFilter(filter);

        // check cache first if not there get from db and put into cache
        Object day = null;
        if(cache.containsKey(key)) {
        	day = cache.get(key);
        } else {
        	try{
        		day = pm.getObjectById(Day.class, key);
        		if(day != null) {
        			FieldAccessor.accessFields(day, null, null, touchFields);
        			cache.put(key, day);
        		}
        	} finally {
        		pm.close();
	        }
        }
        
        return Arrays.asList(day);
    }

    /**
     * Update day with key, with update values
     * 
     * @param filter Day key
     * @param updateFields Fields of day to update
     * @param updatedValues Values to update date fields with
     */
	@Override
	public Object update(Object filter, List<FieldAccessorField> updateFields, List<Object> updatedValues,
			List<FieldAccessorField> touchFields) {
		PersistenceManager pm = pmf.getPersistenceManager();
    	
        Key key = checkFilter(filter);
		
        Object inquiry = null;
    	try{
    		inquiry = pm.getObjectById(Day.class, key);
    		if(inquiry != null) {
    			FieldAccessor.accessFields(inquiry, updateFields, updatedValues, touchFields);
    			cache.remove(key);
    		}
    	} finally {
    		pm.close();
    	}
        
        return inquiry;
	}
}
